package test2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-03-14
 * Time: 23:01
 */
public class TcpEchoClient2 {
    Socket socket = null;

    public TcpEchoClient2(String serverIp, int serverPort) throws IOException {
        socket = new Socket(serverIp, serverPort);
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerNetwork = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream)) {
            while (true) {
                System.out.print("->");
                //1、从控制台输入请求
                if(!scannerConsole.hasNext()) {
                    break;
                }
                String request = scannerConsole.next();
                //2、构造请求，把请求发给服务器
                writer.println(request);
                writer.flush();
                //3、接收服务器返回的响应
                String response = scannerNetwork.next();
                //4、把响应显示到控制台上
                System.out.println(response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient2 tcpEchoClient2 = new TcpEchoClient2("127.0.0.1", 9090);
        tcpEchoClient2.start();
    }
}
